package com.xfsong.demo.controller;

import com.xfsong.demo.common.R;
import com.xfsong.demo.entity.Members;
import com.xfsong.demo.service.MembersService;
import com.xfsong.demo.utils.JwtUtils;
import com.xfsong.demo.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/members")
public class MembersController {

    @Autowired
    private MembersService membersService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @PostMapping("/register")
    public R register(@RequestBody Members members) {
        //检验参数
        System.out.println(members.getUsername());
        if (members.getUsername() == null || members.getUsername().isEmpty()) {
            return R.fail("用户名不能为空,请重新输入！");
        }
        //用户名唯一性验证
        if (membersService.checkUsername(members.getUsername()) > 0) {
            return R.fail("用户名已存在,请更换用户名！");
        }
        if (members.getMobile() == null || members.getMobile().isEmpty()) {
            return R.fail("手机号码不能为空,请重新输入！");
        }
        //验证手机号码是否合法
        if (!members.getMobile().matches("^1[345789]\\d{9}$")) {
            return R.fail("手机号码不合法！");
        }
        //验证手机号码是否已注册
        if (membersService.checkMobile(members.getMobile()) > 0) {
            return R.fail("手机号码已注册,请更换手机号码！");
        }

        if (members.getPassword() == null || members.getPassword().isEmpty()) {
            return R.fail("密码不能为空！");
        }
        //验证密码是否合法
        if (!members.getPassword().matches("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$")) {
            return R.fail("密码不合法！");
        }
        String salt = MD5Utils.generateSalt();
        members.setPassword(MD5Utils.encrypt(members.getPassword(), salt));
        //生成11位数字时间戳
        String timestamp = String.valueOf(System.currentTimeMillis());
        String intTime = timestamp.substring(0, 11);
        members.setCreate_time(intTime);
        members.setSalt(salt);
        int result = membersService.registerMember(members);
        if (result == 0) {
            return R.fail("注册失败！");
        }
        return R.ok(members, "注册成功！");

    }

    //实现登录接口
    @PostMapping("/login")
    public R login(@RequestBody Members members) {
        //检验参数
        if (members.getUsername() == null || members.getUsername().isEmpty()) {
            return R.fail("用户名不能为空,请重新输入！");
        }
        if (members.getPassword() == null || members.getPassword().isEmpty()) {
            return R.fail("密码不能为空，请重新输入！");
        }
        //验证用户名和密码是否匹配
        Members member = membersService.selectMemberByUsername(members.getUsername());
        if (member == null) {
            return R.fail("用户名或密码错误！");
        }
        if (!member.getPassword().equals(MD5Utils.encrypt(members.getPassword(), member.getSalt()))) {
            return R.fail("用户名或密码错误！");
        }
        //登录成功，生成token并存入redis
        //强制转换为String类型
        String token = JwtUtils.generateToken(String.valueOf(member.getId()));
        //hash类型
        redisTemplate.opsForHash().put("user:" + member.getId(), "id", member.getId());
        redisTemplate.opsForHash().put("user:" + member.getId(), "username", member.getUsername());
        redisTemplate.opsForHash().put("user:" + member.getId(), "token", token);
        //设置token过期时间为1小时
        redisTemplate.expire("user:" + member.getId(), Duration.ofDays(3600));

        //定义map
        Map<String, Object> mapResult = new HashMap<>();
        mapResult.put("id", member.getId());
        mapResult.put("username", member.getUsername());
        mapResult.put("token", token);

        return R.ok(mapResult, "登录成功！");
    }

    @GetMapping("/jwtTest")
    public void jwtTest() {
        System.out.println("jwtTest");
    }
}
